RegisterInIs - decorator
The RegisterInIs
decorator is a utility for registering custom methods in the is
utility library for JavaScript. This decorator simplifies the process of extending the functionality of the is
library by allowing you to add custom validation methods that suit your application's specific needs.
Usageโ
The RegisterInIs
decorator can be used to register custom validation methods within the is
utility library. It accepts an optional configuration object as an argument.
@RegisterInIs(configuration?)
class CustomValidator {
// Your custom validation method
}
configuration
(optional): An object that can contain the following properties:customMethod
(optional): A string specifying the custom method to register. If not provided, the decorator will use theinstanceof
method to perform the validation.className
(optional): A string representing the name of the class. If not provided, the decorator will derive it from the instantiated object.
Example #1โ
Here's an example of how to use the RegisterInIs
decorator to register a class in the is
utility library:
import { RegisterInIs } from 'thiis';
@RegisterInIs()
class User {
}
With this usage, you can then use the is
library to call your class method:
import { is } from 'thiis';
console.log(is.User(new User())); // true
const goodArray = [new User(), new User()];
if (goodArray.every(is.User)) {
console.log('All items are User');
}
const badArray = [new User(), new User(), null];
if (badArray.some(is.not_User)) {
console.log('Some items are not User');
}
Example #2โ
Here's an example of how to use the RegisterInIs
decorator to register a custom validation method in the is
utility library:
import { RegisterInIs } from 'thiis';
@RegisterInIs({
customMethod: 'customIsString', // Optional
className: 'MyCustomValidator', // Optional
})
class MyCustomValidator {
// Your custom validation method
public static customIsString(target: unknown): target is string {
return typeof target === 'string';
}
}
With this usage, you can then use the is
library to call your custom validation method:
import { is } from 'thiis';
const result = is.MyCustomValidator('someValue');
console.log(result); // This will invoke your custom validation method
Error Handlingโ
If the customMethod
specified in the configuration is not found within the class, the decorator will throw an error indicating the missing method.
Error: Not found customMethod with name: customIsString
Notesโ
- Ensure that you import the
RegisterInIs
decorator from your library as shown in the examples. - The custom validation method should return a boolean value based on the provided validation logic.